package gw.com.android.ui.bulletin;

import android.app.Dialog;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import gw.com.android.app.GTConfig;
import gw.com.android.greendao.NotifyDataHelper;
import gw.com.android.presenter.BackTopPresenter;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.ui.BaseActivity;
import gw.com.android.utils.ENV;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ThreadPool;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.view.BtnClickListener;
import www.com.library.view.XRecyclerView;

/**
 * @author jett
 * @since 2018-07-27.
 */
public class NotifyCategoryActivity extends BaseActivity {

    public static final int TYPE_ID = ENV.isUat() ? 153 : 68;

    @BindView(R.id.push_category_empty)
    View llEmpty;
    @BindView(R.id.push_category_loading)
    View llLoading;
    @BindView(R.id.push_category_empty_listview)
    ListView lvLoading;
    @BindView(R.id.push_category_listview)
    XRecyclerView rvList;

    private int typeId;
    private NotifyCategoryAdapter mAdapter;
    private NotifyRequest notifyRequest;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_notify_category;
    }

    @Override
    protected void initLayoutView() {
        typeId = getIntent().getIntExtra("typeId", -1);
        String typeName = getIntent().getStringExtra("typeName");
        mTitleBar.setAppTitle(typeName);
        mTitleBar.setBtnClickListener(new BtnClickListener() {
            @Override
            public void onBtnClick(int viewID) {
                if (viewID == R.id.title_left_icon) {
                    finish();
                } else if (viewID == R.id.title_right_text) {
                    PackStatis.getToService("clickRead", "Me", null, null);
                    showDialog();
                }
            }
        });
    }

    @Override
    protected void initViewData() {
        lvLoading.setEnabled(false);
        lvLoading.setFocusable(false);
        lvLoading.setAdapter(new EmptyAdapter());

        HashMap<Integer, String> allCategory = new NotifyRequest().fetchAllCategory();
        mAdapter = new NotifyCategoryAdapter(this, allCategory);
        notifyRequest = new NotifyRequest();
        List<Long> newNotifyId = notifyRequest.getNewNotifyId();
        mAdapter.setNewIds(newNotifyId);
        rvList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        rvList.setAdapter(mAdapter);
        rvList.refreshComplete();
        rvList.setNoMore(true);
        new BackTopPresenter(this, rvList).calcNavigationBar(true);
        rvList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadFromNet();
            }

            @Override
            public void onLoadMore() {
            }
        });
        new CategoryTask().execute(typeId);
        rvList.setRefreshing(true);
    }

    @Override
    public void registerRxBus() {
        Disposable noticeRegister = RxBus.getInstance().register("notification_data_update", Boolean.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean isConnection) throws Exception {
                        new CategoryTask().execute(typeId);
                    }
                });
        bindSubscription(noticeRegister);
    }

    private void refreshUi(List<NotifyData> list) {
        llLoading.setVisibility(View.GONE);
        if (list == null || list.isEmpty()) {
            llEmpty.setVisibility(View.VISIBLE);
            rvList.setNoMore(false);
        } else {
            llEmpty.setVisibility(View.GONE);
            rvList.setNoMore(true);

            boolean showOneKeyRead = false;
            for (NotifyData data : list) {
                if (data != null && !data.isReaded) {
                    showOneKeyRead = true;
                    break;
                }
            }
            if (showOneKeyRead) {
                mTitleBar.setRightText(R.string.push_one_key_read);
            } else {
                mTitleBar.setRightText("");
            }
        }
        mAdapter.setDatas(list);
    }

    private void showDialog() {
        long dialogCount = GTConfig.instance().getLongValue("notify_one_key_dialog_count", 0);
        if (dialogCount >= 3) {
            setAllNoticeReaded();
            return;
        }
        dialogCount += 1;
        GTConfig.instance().setLongValue("notify_one_key_dialog_count", dialogCount);

        final Dialog dialog = new Dialog(this, R.style.dialog_loading_bar_no_frame);
        View dialogView = View.inflate(this, R.layout.dialog_one_key_read, null);
        dialogView.findViewById(R.id.action_btn_neg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.action_btn_pos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                setAllNoticeReaded();
            }
        });
        dialog.setContentView(dialogView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        dialog.show();
    }

    private void setAllNoticeReaded() {
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                NotifyDataHelper.setAllNoticeReaded(typeId);
                NotifyDataHelper.notifyChange();
            }
        });
    }

    private class CategoryTask extends AsyncTask<Integer, Void, List<NotifyData>> {

        @Override
        protected List<NotifyData> doInBackground(Integer... params) {
            if (params != null && params.length > 0) {
                return NotifyDataHelper.getNotify(params[0]);
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<NotifyData> notifyData) {
            refreshUi(notifyData);
        }

    }

    private void loadFromNet() {
        if (notifyRequest == null) {
            notifyRequest = new NotifyRequest();
        }
        notifyRequest.getNoticeList(GTConfig.instance().mCurName, new HttpCallback<List<NotifyData>>() {
            @Override
            public void onSuccess(List<NotifyData> result) {
                rvList.refreshComplete();
                if (mAdapter != null) {
                    List<Long> newNotifyId = notifyRequest.getNewNotifyId();
                    mAdapter.setNewIds(newNotifyId);
                }
            }

            @Override
            public void onFailure(Exception e) {
                rvList.refreshComplete();
            }
        });
    }

    private class EmptyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return 8;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_push_category_empty, parent, false);
            }
            return convertView;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (notifyRequest != null && mAdapter != null) {
            notifyRequest.deleteNewNotifyId(mAdapter.getNotifyIds());
        }
    }
}
